import React, { Component } from 'react';
import "../styles/Login.scss"
import * as service from "../api/index";
import { Link, withRouter } from 'react-router-dom'
import { Toast } from 'antd-mobile'

class Login extends Component {
    constructor(props) {
        super(props);
        this.state = {
            phone: '',
            pass: ''
        }
    }
    handleChange(e) {
        this.setState({ [e.target.name]: e.target.value })
    }
    async login() {
        if (this.state.pass && this.state.phone) {
            var res = await service.user_login();

            let i = res.data.findIndex((item) => { return item.phone == this.state.phone && item.pass == this.state.pass })
            if (i == -1) {
                Toast.show({
                    content: '请输入正确的账户密码'
                })
            } else {
                Toast.show({
                    content: '登陆成功'
                })
                this.props.history.push('/index');
            }

        } else {
            Toast.show({
                content: '请输入用户信息'
            })
        }
    }
    render() {
        return (
            <div className='login'>
                <div className="logo"><div></div></div>
                <div className='title'>账号密码登录</div>
                <div className="box">
                    <input
                        type="text"
                        name='phone'
                        value={this.state.phone}
                        onChange={(e) => { this.handleChange(e) }}
                        placeholder='请输入账号'
                    />
                    <input
                        type="password"
                        name='pass'
                        value={this.state.pass}
                        onChange={(e) => { this.handleChange(e) }}
                        placeholder='请输入密码'
                    />
                    <button onClick={() => { this.login() }}>登录</button>
                    <Link to={"/register"}>注册新用户</Link>
                </div>
            </div>
        );
    }
}

export default withRouter(Login);